<?php

namespace Portal\Api;

use PhalApi\Api;
use Portal\Domain\Admin as AdminDomain;
use PhalApi\Exception\BadRequestException;

/**
 * 认证中心
 * @author chenwengen 20240420
 */
class Auth extends Api
{
    public function getRules()
    {
        return [
            'login' => [
                'username' => array('name' => 'username', 'require' => true, 'desc' => '账号','source' => 'post'),
                'password' => array('name' => 'password', 'require' => true, 'desc' => '密码','source' => 'post'),
                'captchaKey' => array('name' => 'captchaKey', 'require' => true, 'desc' => '验证码key','source' => 'post'),
                'captchaCode' => array('name' => 'captchaCode', 'require' => true, 'desc' => '验证码','source' => 'post'),
              ],
            'captcha' => [],
            ];
    }

    /**
     * 管理员登录
     * @desc 根据管理员账号和密码，进行登录
     */
    public function login()
    {
        $domain = new AdminDomain();
        $captchaKey = $this->captchaKey;
        $captchaCode = $this->captchaCode;
        //验证码验证
        if (strtolower($captchaCode) != strtolower(\PhalApi\DI()->cache->get($captchaKey))) {
            throw new BadRequestException("验证码错误", 3);
        } else {
            //删除缓存key
            \PhalApi\DI()->cache->delete($captchaKey);
        }
        $returnData = $domain->login($this->username, $this->password);


        return $returnData;
    }

    /**
     * 获取验证码
     * @desc 获取验证码
     * @return string captchaKey 验证码key
     * @return string captchaBase64 验证码base64位图片
     * @exception 400 非法请求，参数传递错误
     */
    public function captcha()
    {

        $captcha = new \Gregwar\Captcha\CaptchaBuilder();
        $captcha->setBackgroundColor(240, 240, 240);
        $captcha->build(120, 40);
        //存缓存
        $phrase = $captcha->getPhrase();
        $cacheKey = md5($phrase.microtime(true));
        \PhalApi\DI()->cache->set($cacheKey, $phrase, 60);
        // $di = \PhalApi\DI();
        // $di->response->setCode('100');

        return [
            'captchaKey' => $cacheKey,
            'captchaBase64' => $captcha->inline(),
        ];
    }

}
